<template>
  <el-time-picker @change="change" :format="time_format" is-range v-model="time" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围">
  </el-time-picker>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance();
let props = defineProps(["start", "end", "format"]);
const emit = defineEmits(["update:start", "update:end"]);

let time = ref([]);

let time_format = computed(() => {
  return props.format ? props.format : "HH:mm:ss";
});

let getTime = (e?) => {
  let now = proxy.$utils.dateTimeFormateFn(new Date());
  let time = `${now}`;
  if (e) {
    time = `${now} ${e}`;
  }
  var d = new Date(time);
  d = d.getFullYear() > 0 ? d : new Date(Date.parse(time.replace(/-/g, "/"))); //为了兼容ios
  var year = d.getFullYear();
  var month = d.getMonth() + 1;
  var day = d.getDate();
  var hour = d.getHours();
  var minutes = d.getMinutes();
  return { year, month, day, hour, minutes };
};

let change = (e) => {
  let type = "hourMinutesSeconds";
  if (props.format) {
    switch (props.format) {
      case "HH:mm":
        type = "hourMinutes";
        break;

      default:
        break;
    }
  }
  emit("update:start", proxy.$utils.dateTimeFormateFn(new Date(e[0]), type));
  emit("update:end", proxy.$utils.dateTimeFormateFn(new Date(e[1]), type));
};

watch(
  () => props.start,
  (newValue, oldValue) => {
    if (newValue) {
      let start = getTime(props.start);
      let end = getTime(props.end);
      time.value = [
        new Date(start.year, start.month, start.day, start.hour, start.minutes),
        new Date(end.year, end.month, end.day, end.hour, end.minutes),
      ];
    } else {
      let now = getTime();
      time.value = [
        new Date(now.year, now.month, now.day, now.hour, now.minutes),
        new Date(now.year, now.month, now.day, 23, now.minutes),
      ];
      change(time.value);
    }
  },
  { deep: true, immediate: true }
);
</script>



<style lang="scss" scoped>
</style>